package com.jd.orm.framework.core.transaction;

import java.sql.SQLException;

import javax.sql.DataSource;

import com.jd.orm.framework.core.exception.DbError;
import com.jd.orm.framework.core.exception.SystemException;

/**
 * 
 * ClassName: JdbcResourceManager <br/>
 * Function: JdbcResourceManager <br/>
 * Reason: TODO ADD REASON. <br/>
 * date: 2014-5-13 上午9:24:09 <br/>
 * 
 * @author liubing1@jd.com
 * @version
 * @since up JDK 1.5
 */
public class JdbcResourceManager implements IResourceManager<JdbcSession> {
	
	protected final DataSource dataSource;

	/**
	 * 
	 * Creates a new instance of JdbcResourceManager.
	 * 
	 * @param dataSource
	 */
	public JdbcResourceManager(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	public Class<JdbcSession> getResourceType() {
		return JdbcSession.class;
	}

	/**
	 * beginTransaction
	 */
	public JdbcSession beginTransaction(TransactionDefinition definition,
			boolean active) {
		JdbcSession session = new JdbcSession(dataSource);
		if (active) {
			session.beginTransaction(definition);
		}
		return session;
	}

	public void commitTransaction(JdbcSession resource) {
		if (resource.isTransactionActive()) {
			resource.commitTransaction();
		}
		// resource.closeSession();
	}

	public void rollbackTransaction(JdbcSession resource) throws Exception {
		try {
			if (resource.isTransactionActive()) {
				resource.rollbackTransaction();
			}
		} catch (Exception ex) {
			throw SystemException.unchecked(ex, DbError.TRANSACTION_ERROR);
		} finally {
			resource.closeSession();
		}
	}

	public void close() {
		try {
			dataSource.getConnection().close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw SystemException.unchecked(e, DbError.IO_ERROR);
		}
	}
}
